package com.dongdongshop.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.dongdongshop.data.Result;
import com.dongdongshop.enums.ResultEnum;
import com.dongdongshop.page.PageResult;
import com.dongdongshop.pojo.TbContent;
import com.dongdongshop.pojo.TbContentCategory;
import com.dongdongshop.service.TbContentCategoryService;
import com.dongdongshop.service.TbContentService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

@Controller
@RequestMapping("content")
public class TbContentController {
    private Logger logger = LoggerFactory.getLogger(TbContentController.class);

    @DubboReference
    private TbContentService contentService;
    @DubboReference
    private TbContentCategoryService categoryServicee;

    @RequestMapping("show")
    public String show(){
        return "admin/content";
    }

    @RequestMapping("listContent")
    @ResponseBody
    public Result listContent(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "3") Integer pageSize){
        try {
            PageResult<TbContent> listContent = contentService.listContent(pageNum,pageSize);
            return Result.OK().setData(listContent);
        }catch (Exception e){
            logger.info("查询广告信息出现异常: {}",e);
            return Result.response(ResultEnum.SELECT_MESSAGE_ERROE);
        }
    }




    @RequestMapping("getCategroys")
    @ResponseBody
    public Result getCategroys(){
        try {
            List<TbContentCategory> cates = categoryServicee.getCategroys();
            return Result.OK().setData(cates);
        }catch (Exception e){
            logger.info("查询广告信息出现异常: {}",e);
            return Result.response(ResultEnum.SELECT_MESSAGE_ERROE);
        }
    }





    @RequestMapping("addContent")
    @ResponseBody
    public Result addContent(TbContent content){
        try {
            contentService.addContent(content);
            return Result.OK();
        }catch (Exception e){
            logger.info("增加广告信息出现异常: {}",e);
            return Result.response(ResultEnum.SELECT_MESSAGE_ERROE);
        }
    }



    @RequestMapping("updateContent")
    @ResponseBody
    public Result updateContent(TbContent content){
        try {
            contentService.updateContent(content);
            return Result.OK();
        }catch (Exception e){
            logger.info("增加广告信息出现异常: {}",e);
            return Result.response(ResultEnum.SELECT_MESSAGE_ERROE);
        }
    }


    @RequestMapping("toUpdate")
    @ResponseBody
    public Result toUpdate(Long id){
        try {
            TbContent content = contentService.selectContentById(id);
            return Result.OK().setData(content);
        }catch (Exception e){
            logger.info("增加广告信息出现异常: {}",e);
            return Result.response(ResultEnum.SELECT_MESSAGE_ERROE);
        }
    }




    @RequestMapping("deleteConts")
    @ResponseBody
    public Result deleteConts(Long[] ids){
        try {
            contentService.deleteConts(ids);
            return Result.OK();
        }catch (Exception e){
            logger.info("批量删除方法异常 {}",e.toString());
            return Result.response(ResultEnum.DELETE_MESSAGE_ERROE);
        }
    }









    @RequestMapping("upload")
    @ResponseBody
    public Result upload(@RequestParam("addFile") MultipartFile addFile){
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String http = "https://";
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tAzLoxGg1pwiTALqmNQ";
        String accessKeySecret = "QnvvcqC7AA0CQ4KXyCnT5gePimSj9v";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "ssl-2204";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "imageContent/" + addFile.getOriginalFilename();
        //https://ssl-2204.oss-cn-beijing.aliyuncs.com/image/collection_pic.jpg
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(http + endpoint, accessKeyId, accessKeySecret);
        try {
            // 创建PutObject请求。
            InputStream inputStream = addFile.getInputStream();
            ossClient.putObject(bucketName, objectName, inputStream);
            String imageUrl = "https://" + bucketName + "." + endpoint + "/" + objectName;
            return Result.OK().setData(imageUrl);
        } catch (Exception oe) {
            oe.printStackTrace();
            return Result.ERROR();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
    @RequestMapping("uploadUp")
    @ResponseBody
    public Result uploadUp(@RequestParam("updateFile") MultipartFile updateFile){
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String http = "https://";
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tAzLoxGg1pwiTALqmNQ";
        String accessKeySecret = "QnvvcqC7AA0CQ4KXyCnT5gePimSj9v";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "ssl-2204";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "imageContent/" + updateFile.getOriginalFilename();
        //https://ssl-2204.oss-cn-beijing.aliyuncs.com/image/collection_pic.jpg
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(http + endpoint, accessKeyId, accessKeySecret);
        try {
            // 创建PutObject请求。
            InputStream inputStream = updateFile.getInputStream();
            ossClient.putObject(bucketName, objectName, inputStream);
            String imageUrl = "https://" + bucketName + "." + endpoint + "/" + objectName;
            return Result.OK().setData(imageUrl);
        } catch (Exception oe) {
            oe.printStackTrace();
            return Result.ERROR();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
